package com.health.task;

import com.health.entity.BannedUsers;
import com.health.service.IBannedUsersService;
import com.health.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

@EnableScheduling
@Configuration
@Slf4j
public class UnblockingUsersTask {

    @Autowired
    private IBannedUsersService bannedUsersService;

    @Autowired
    private IUserService userService;

    /**
     * 每天凌晨12点执行定时解封操作
     */
//    @Scheduled(cron = "0/5 * * * * ?")
    @Scheduled(cron = "0 0 0 * * ?")
    @Transactional
    public void unblockingUsers(){
        LocalDateTime now = LocalDateTime.now();
        //拿到被封禁用户列表
        List<BannedUsers> banUsers = bannedUsersService.listBanUser();
        banUsers.forEach(item ->{
            LocalDateTime createTime = item.getCreateTime();
            // 拿到被封禁用户的封禁时间与当前时间对比的到已封禁天数
            long daysBetween = ChronoUnit.DAYS.between(createTime, now);
            // 用已封禁天数减去用户封禁时间
            int num = (int) (daysBetween - item.getBanTime());
            if (item.getBanTime() != -1 && num >= 0){
                //如果num >= 0 表现该用户封禁时间已到，执行解封操作
                bannedUsersService.removeById(item.getId());
                // 相应的更新user表is_lock状态
                userService.unblockingUser(item.getUserId());
            }
        });
    }
}
